<?php
/**
 * The controller to manage information of sale program.
 *
 */
$loader->requireOnce('ordo/SaleServiceMap.class.php');

class C_SaleProgram extends Controller {
	
	function C_SaleProgram($template_mod = "general") {
		parent::Controller();
		if (Celini::getCurrentController() == 'SaleProgram') {
			$menu =& Menu::getInstance();
			$menu->currentSection = 'admin';
		}
		$this->template_mod = $template_mod;			
		$this->view->path = 'sale_program';
		$this->setLayout('admin');
	}
	
    /**
     * Action to open the view for managing sale program.
     */
    public function actionManagement() {
        return $this->view->render('sale_program_management.html');
    }
    
    /**
     * Open the view to map sale_program/examination_type with service.
     *
     */
    public function actionMapSaleProgramService() {
    	$saleProgramList = Celini::newORDO('SaleProgram')->getAllSalePrograms();
    	$serviceGroupList = Celini::newORDO('ServiceGroup')->listAll();
		
    	// assign parameters for the view
    	$this->assign('saleProgramList', $saleProgramList);
    	$this->assign('serviceGroupList', $serviceGroupList);
    	
    	return $this->view->render('sale_program_service.html');
    }
    
    public function actionCheckSaleProgramCode() {
    	$code = $_GET['code'];
    	$saleId = $_GET['sale_program_id'];
    	$res = Celini::newORDO('SaleProgram')->checkCode($code, $saleId);    	    	
    	return $res;
    }
    
    
    /**
     * Load mapped services of the specific sale program.
     *
     */
    public function actionLoadMappedServiceAjax() {
    	$saleProId = $_GET['sale_program_id'];
    	// get service list of sale program
    	$mappedList = Celini::newORDO('SaleServiceMap')->getServiceBySaleProgram($saleProId);
    	return json_encode($this->renderServiceListOfSalePro($mappedList));
    }
    
    /**
     * Render the content of sale_service list for the view.
     *
     * @param Array $mappedList The list of sale_service 
     * @return The array of html content
     */
    private function renderServiceListOfSalePro($mappedList) {
    	$body = "";
    	foreach ($mappedList as $row) {
    		$aRow = "";
    		$id = $row['service_id'];
    		$checkedYes = "";
    		$checkedNo = "";
    		if ($row['percent'] == 'yes') {
    			$checkedYes = "checked=\"checked\"";
    		} else {
    			$checkedNo = "checked=\"checked\"";
    		}
    		// buid a row of 'sale_service' table
    		$aRow .= "<tr id=\"$id\">";
    		$aRow .= "<td class=\"first\">
    		              <input type=\"hidden\" id=\"serviceId[]\" value=\"$id\">
    		              <span>$row[name]</span>
    		          </td>";
    		$aRow .= "<td>
    		              <input type=\"text\" id=\"value_$id\" name=\"value_$id\" value=\"$row[value]\"
    		                  onkeyup=\"javascript:this.value=this.value.replace(/[^0-9]/g, '');\">
    		          </td>";
    		$aRow .= "<td>
    		              <input type=\"radio\" id=\"percent_$id\" name=\"percent_$id\" value=\"yes\" $checkedYes>% 
                          <input type=\"radio\" id=\"percent_$id\" name=\"percent_$id\" value=\"no\" $checkedNo>" . L10nHelper::_("VND") . "
                      </td>";
            $aRow .= "<td class=\"last\">
                          <a href=\"javascript:removeService($id);\" title=\"" . L10nHelper::_("Delete service") . "\"> 
                              <img src=\"../images/remove_small.png\" alt=\"" . L10nHelper::_("Delete") . "\"></img>
                          </a>
                      </td>";
    		$aRow .= "</tr>";
    		
    		$body .= $aRow;
    	}
    	return array('body' => $body);
    }
    
    /**
     * Save the mapping of sale program and service.
     *
     */
    public function actionSaveSaleServiceAjax() {
    	$saleProId = $_POST['sale_program_id'];
    	$saleServiceArr = explode(';', $_POST['sale_service_array']);
    	
    	$saleService = Celini::newORDO('SaleServiceMap');
    	// delete old mapping of sale_service
    	$saleService->deleteServiceOfSaleProgram($saleProId);
    	
    	// save new mapping of sale_service
    	foreach ($saleServiceArr as $item) {
    		$item = split(",", $item);
    		$newObj = Celini::newORDO('SaleServiceMap');
    		$data = array (
                'sale_program_id' => $saleProId,
                'service_id' => $item[0],
                'value' => $item[1],
                'percent' => $item[2],
                'item_type' => SaleServiceMap::SALE_ITEM_TYPE
            );
        
            $newObj->populateArray($data);
            $newObj->persist();
    	}
    }
    
	public function actionListSaleProgram() {
		$saleProgramList = Celini::newORDO('SaleProgram')->listAll();
		
		$this->assign('saleProgramList', $saleProgramList);
		return $this->view->render('list_sale_program.html');
	}
	
	public function actionSaveSaleProgramAjax() {
		$nameField	=	L10nHelper::changeField(L10nHelper::getLocale(),"name");
		$desField	=	L10nHelper::changeField(L10nHelper::getLocale(),"description");
			
		$locales = L10nHelper::getSupportedLocales();
		$name = Sanitize::removeSpaces($_POST['name']);
		$saleProgram = Celini::newORDO('SaleProgram');
	   	if (isset($_POST['sale_program_id']) && $_POST['sale_program_id'] != "") {
            $saleProgram->setup($_POST['sale_program_id']);
       	}
       	
       	$id = $saleProgram->get_id();
       	//save to localize table
		if (id == 0) {
			//add new
			$data = array('code' => $_POST['code']);		
	       	foreach ( $locales as $lo => $la ) {
	       			$nameField	=	L10nHelper::changeField($lo,"name");
					$desField	=	L10nHelper::changeField($lo,"description");
	       			$data[$nameField] = $name;
	       			$data[$desField] = $_POST['description'];
	       	}		                        
		} else {	
			//udpate		
			$data = array(
				$nameField => $name,
				$desField	=> $_POST['description'],
				'code' => $_POST['code']
			);			                        
			$saleProgram->setup($id);
		}
		
	   $saleProgram->populateArray($data);
	   $saleProgram->persist();	 
	}
	
	public function actionListAliveSaleProgramAjax(){
		$alive_sale_program_list = Celini::newORDO('SaleProgram')->getCurrentSalePrograms();
		$saleProgramList = Celini::newORDO('SaleProgram')->getNotCurrentSalePrograms();
		
		$this->assign('saleProgramList', $saleProgramList);
		$this->assign('alive_sale_program_list', $alive_sale_program_list);
		// TODO: @LOCALIZATION
		$this->assign('today', date('d/m/Y'));
		$orders	=	L10nHelper::getYMDorder();
        $this->assign('datePart_0', $orders[0]);
        $this->assign('datePart_1', $orders[1]);
        $this->assign('datePart_2', $orders[2]);		
		
		return $this->view->render('list_alive_sale_program.html');	
	}
	
	public function actionSaveSaleProgramStoreAjax(){
		$obj = new DateObject();
		if (isset($_POST['start_dd']) && isset($_POST['start_mm']) && isset($_POST['start_yyyy'])
		&& isset($_POST['end_dd']) && isset($_POST['end_mm']) && isset($_POST['end_yyyy'])) {
			//add
	        $start = $_POST['start_dd'] . "/" . $_POST['start_mm']. "/" . $_POST['start_yyyy'];
	        $end = $_POST['end_dd'] . "/" . $_POST['end_mm']. "/" . $_POST['end_yyyy'];
		} else if (isset($_POST['edit_start_dd']) && isset($_POST['edit_start_mm']) && isset($_POST['edit_start_yyyy'])
		&& isset($_POST['edit_end_dd']) && isset($_POST['edit_end_mm']) && isset($_POST['edit_end_yyyy'])) {
			//edit
			$start = $_POST['edit_start_dd'] . "/" . $_POST['edit_start_mm']. "/" . $_POST['edit_start_yyyy'];
	        $end = $_POST['edit_end_dd'] . "/" . $_POST['edit_end_mm']. "/" . $_POST['edit_end_yyyy'];			
		} else {
			return false;
		}
		$start_dateObj = $obj->createFromVN($start);	
			
		if ($start_dateObj->isValid()) {
			$start_date = $start_dateObj->toISO();			 		
		} else {
			return false;
		}
		
		$end_dateObj = $obj->createFromVN($end);		
		if ($end_dateObj->isValid()) {
			$end_date = $end_dateObj->toISO();			 		
		} else {
			return false;
		}		
		$data = array (
	       	
			'sale_program_id' => $_POST['sale_program_id'],
	       	'start_date' => $start_date,
		   	'end_date' => $end_date
	   	);
		$saleProgram = Celini::newORDO('SaleProgramStore');
	   	if (isset($_POST['sale_program_store_id']) && $_POST['sale_program_store_id'] != "") {
            $saleProgram->setup($_POST['sale_program_store_id']);
       	}
	   	$saleProgram->populateArray($data);
	   	$saleProgram->persist();	
	}
}
?>